package cn.com.generaldata.os.service.common;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import cn.com.generaldata.os.constant.BillboardConstant;
import cn.com.generaldata.os.constant.FilterConstant;
import cn.com.generaldata.os.dao.intf.BaseDAOInterface;
import cn.com.generaldata.os.job.AutoPushingScheduler;
import cn.com.generaldata.os.newpojo.ReportType;
import cn.com.generaldata.os.newpojo.SystemCodedic;
import cn.com.generaldata.os.paging.Filter;
import cn.com.generaldata.os.paging.FilterRule;
import cn.com.generaldata.os.paging.Result;
import cn.com.generaldata.os.pojo.Billboard;
import cn.com.generaldata.os.pojo.BillboardIndustry;
import cn.com.generaldata.os.pojo.BillboardIndustryReports;
import cn.com.generaldata.os.pojo.BillboardRule;
import cn.com.generaldata.os.pojo.BillboardUser;
import cn.com.generaldata.os.pojo.Report;
import cn.com.generaldata.os.pojo.Unit;
import cn.com.generaldata.os.pojo.User;
import cn.com.generaldata.os.service.impl.UnitService;
import cn.com.generaldata.os.service.intf.ReportServiceInterface;
import cn.com.generaldata.os.vo.RportOfIndustryVO;

@Component
public class AutoPushingService {

	private static Logger log = LoggerFactory.getLogger(AutoPushingService.class);

	@Autowired
	@Qualifier("baseDAO")
	private BaseDAOInterface<BillboardRule> billboardRuleDAO;

	@Autowired
	@Qualifier("baseDAO")
	private BaseDAOInterface<BillboardIndustry> billboardIndustryDAO;

	@Autowired
	@Qualifier("baseDAO")
	private BaseDAOInterface<BillboardIndustryReports> billboardIndustryReportsDAO;

	@Autowired
	private UnitService unitService;

	@Autowired
	@Qualifier("baseDAO")
	private BaseDAOInterface<SystemCodedic> sysCodedicDAO;

	@Autowired
	@Qualifier("baseDAO")
	private BaseDAOInterface<Billboard> billboardDAO;

	private final SimpleDateFormat sfd = new SimpleDateFormat("yyyy/MM");
	private final SimpleDateFormat sf = new SimpleDateFormat("yyyyMM");

	@Autowired
	@Qualifier("baseDAO")
	private BaseDAOInterface<BillboardUser> billboardUserDAO;

	@Autowired
	@Qualifier("baseDAO")
	private BaseDAOInterface<User> userDAO;

	@Autowired
	private ReportServiceInterface reportService;

	@Autowired
	private AutoPushingScheduler autoPushingScheduler;

	@Autowired
	private StatSystemService statSystemService;

	public List<BillboardRule> queryAllBillboardRules(String title) {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.ASC);
		filter.setSortBy("dateType");

		if (StringUtils.isNotBlank(title)) {
			filter.addRule(new FilterRule(FilterConstant.LIKE, "billboardTitle", "%" + title + "%"));
		}

		return billboardRuleDAO.find(BillboardRule.class, filter, null);
	}

	public List<cn.com.generaldata.os.vo.ReportVO> turnQueryReports(String userId, String billId) {
		User user = userDAO.get(User.class, userId);
		Filter filter = new Filter();
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "user.id", user.getUserUnit().getId()));
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "billboard.id", billId));
		List<cn.com.generaldata.os.vo.ReportVO> reportList = new ArrayList<cn.com.generaldata.os.vo.ReportVO>();
		List<BillboardUser> billboardUsers = billboardUserDAO.find(BillboardUser.class, filter, null);

		if (billboardUsers != null && billboardUsers.size() > 0) {
			for (BillboardUser billUser : billboardUsers) {
				Billboard bill = billUser.getBillboard();
				Filter filter2 = new Filter();
				filter2.addRule(new FilterRule(FilterConstant.EQUAL, "id", bill.getBillboardIndustryId()));
				// filter2.addRule(new FilterRule(FilterConstant.EQUAL,
				// "billboardContent", bill.getBillboardContent()));
				// filter2.addRule(new FilterRule(FilterConstant.LIKE, "users",
				// "%" + user.getUserUnit().getId() + "%"));
				List<BillboardIndustry> find = billboardIndustryDAO.find(BillboardIndustry.class, filter2, null);
				if (find != null && find.size() > 0) {
					BillboardIndustry bi = find.get(0);
					Set<BillboardIndustryReports> brs = bi.getbIndustryReports();
					if (brs != null && brs.size() > 0) {
						for (BillboardIndustryReports br : brs) {
							List<Report> list = reportService.queryReportsByBillboardUser(br.getReportTypeCode(),
									br.getReportTypeTime(), br.getReportYearTime(), br.getBillboardTimeQuarter(),
									br.getBillboardTime(), br.getReportTypeSystem(), userId);
							if (list == null) {
								cn.com.generaldata.os.vo.ReportVO report = new cn.com.generaldata.os.vo.ReportVO();
								report.setReportDomainName(br.getReportTypeSystem() + "中的" + br.getReportTypeName()
										+ "未上报");
								report.setOperatorId(userId);
								report.setReportTypeId(br.getReportTypeCode());
								report.setReportTimetype(br.getReportTypeTime());
								String billboardIndustryId = br.getBillboardIndustryId();
								BillboardIndustry billboardIndustry = billboardIndustryDAO.get(BillboardIndustry.class,
										billboardIndustryId);
								report.setReportUnitIndustry(billboardIndustry.getIndustryId());
								report.setReportYearTime(br.getReportYearTime());
								String billboardDate = br.getBillboardTime();
								if (br.getBillboardTimeQuarter() != null && !"".equals(br.getBillboardTimeQuarter())) {
									report.setReportQuarter(br.getBillboardTimeQuarter());
								} else {
									String[] yearMonth = billboardDate.split("/");
									int month = Integer.parseInt(yearMonth[1]);
									if (month >= 1 && month < 4) {
										report.setReportQuarter("1");
									}
									if (month >= 4 && month < 7) {
										report.setReportQuarter("2");
									}
									if (month >= 7 && month < 10) {
										report.setReportQuarter("3");
									}
									if (month >= 10 && month <= 12) {
										report.setReportQuarter("4");
									}
								}
								report.setReportVersion("v1.00.00");
								report.setReportMonth(billboardDate);
								reportList.add(report);
							}
						}

					}
				}
			}

		}
		return reportList;
	}

	public int queryBillboardCompletReposts(List<String> bIndustryReports, String units) {
		int tjReports = 0;
		BillboardIndustryReports billboardIndustryReports = new BillboardIndustryReports();
		for (int i = 0; i < bIndustryReports.size(); i++) {
			billboardIndustryReports = billboardIndustryReportsDAO.get(BillboardIndustryReports.class,
					bIndustryReports.get(i));
			tjReports += reportService.queryReportsByBillboardTime(billboardIndustryReports.getReportTypeCode(),
					billboardIndustryReports.getReportTypeTime(), billboardIndustryReports.getReportYearTime(),
					billboardIndustryReports.getBillboardTimeQuarter(), billboardIndustryReports.getBillboardTime(),
					billboardIndustryReports.getReportTypeSystem(), units);
		}

		return tjReports;
	}

	public List<RportOfIndustryVO> queryCompletReposts(List<String> bIndustryReports, String users) {
		BillboardIndustryReports billboardIndustryReports = new BillboardIndustryReports();
		String[] split = users.split(",");
		List<RportOfIndustryVO> roiList = new ArrayList<RportOfIndustryVO>();
		for (String user : split) {
			if (!"".equals(user)) {
				RportOfIndustryVO roi = new RportOfIndustryVO();
				Unit userById = unitService.queryUnitById(user);
				roi.setUserId(userById.getId());
				roi.setUserName(userById.getUnitName());
				List<RportOfIndustryVO> rsList = new ArrayList<RportOfIndustryVO>();
				int j = 0;
				for (int i = 0; i < bIndustryReports.size(); i++) {
					RportOfIndustryVO rs = new RportOfIndustryVO();
					Set<User> userSet = userById.getUsers();
					billboardIndustryReports = billboardIndustryReportsDAO.get(BillboardIndustryReports.class,
							bIndustryReports.get(i));
					for (User iuser : userSet) {
						List<Report> list = reportService.queryReportsByBillboardUser(
								billboardIndustryReports.getReportTypeCode(),
								billboardIndustryReports.getReportTypeTime(),
								billboardIndustryReports.getReportYearTime(),
								billboardIndustryReports.getBillboardTimeQuarter(),
								billboardIndustryReports.getBillboardTime(),
								billboardIndustryReports.getReportTypeSystem(), iuser.getId());
						if (list != null) {
							Report report = list.get(0);
							rs.setUserId(report.getId());
							rs.setUserName(billboardIndustryReports.getReportTypeSystem() + "中的"
									+ billboardIndustryReports.getReportTypeName() + "已上报");
							rs.setStauts("1");
							j++;
						} else {
							rs.setUserId("1");
							rs.setUserName(billboardIndustryReports.getReportTypeSystem() + "中的"
									+ billboardIndustryReports.getReportTypeName() + "未上报");
							rs.setStauts("0");
						}
					}
					rsList.add(rs);
				}
				// 浼佷笟宸插畬鎴愪笂鎶�
				if (j == bIndustryReports.size()) {
					roi.setStauts("1");
					j = 0;
				} else {
					roi.setStauts("0");
				}
				roi.setReportName(rsList);
				roiList.add(roi);
			}
		}
		return roiList;
	}

	public BillboardIndustry queryAllBillboardIndustry(String id) {
		return billboardIndustryDAO.get(BillboardIndustry.class, id);
	}

	public List<BillboardIndustry> queryAllBillboardIndustrys(String title, String content, String unit,
			String operatorId) {
		// Filter filter = new Filter();
		// filter.setOrder(FilterConstant.ASC);
		// filter.setSortBy("dateType");
		// filter.addRule(new FilterRule(FilterConstant.EQUAL, "operator.id",
		// operatorId));
		List<BillboardIndustry> list = new ArrayList<BillboardIndustry>();
		HashMap map = new HashMap();
		String hql = "from BillboardIndustry where operator.id=:operatorId";
		map.put("operatorId", operatorId);
		if (StringUtils.isNotBlank(title)) {
			// filter.addRule(new FilterRule(FilterConstant.LIKE,
			// "billboardTitle", "%" + title + "%"));
			hql += " and billboardTitle like :title";
			map.put("title", "%" + title + "%");
		}
		if (StringUtils.isNotBlank(content)) {
			// filter.addRule(new FilterRule(FilterConstant.LIKE,
			// "billboardContent", "%" + content + "%"));
			hql += " and billboardContent like :content";
			map.put("content", "%" + content + "%");
		}
		if (StringUtils.isNotBlank(unit)) {
			Filter filterUnit = new Filter();
			filterUnit.addRule(new FilterRule(FilterConstant.LIKE, "unitName", "%" + unit + "%"));
			Result units = unitService.queryUnits(filterUnit, null);
			if (units.getOperationResult() != null && units.getOperationResult().size() > 0) {
				hql += " and (";
				List<Unit> operationResult = (List<Unit>) units.getOperationResult();
				for (int i = 0; i < operationResult.size(); i++) {
					Unit unit2 = operationResult.get(i);
					hql += " users like :uid" + i + " or";
					map.put("uid" + i, "%" + unit2.getId() + "%");
				}
				hql = hql.substring(0, hql.length() - 2);
				hql += ")";
			} else {
				hql += " and 1=2";
				// filter.addRule(new FilterRule(FilterConstant.LIKE,
				// "billboardTitle", "%" + title + "%"));
			}
		}
		hql += " order by dateType";
		Result hqlParam = billboardIndustryDAO.hqlParam(hql, map, null);
		if (hqlParam.getOperationResult() != null && hqlParam.getOperationResult().size() > 0) {
			list = (List<BillboardIndustry>) hqlParam.getOperationResult();
		}
		return list;
	}

	public Integer queryBillByReport(String reportTypeId, String unitId, String timeType, String yearType,
			String timeDate, String quarter) {
		// Filter filter = new Filter();
		HashMap param = new HashMap();
		String hql = "from BillboardIndustryReports br where reportTypeCode=:reportTypeCode and reportTypeTime=:reportTypeTime and billboardTime=:billboardTime and  exists (select bi.id from BillboardIndustry as bi where br.billboardIndustryId=bi.id and bi.users like :unitId)";
		// 年报
		if ("1".equals(timeType)) {
			hql += " and reportYearTime=:reportYearTime";
			param.put("reportYearTime", yearType);
		}
		// 季报
		else if ("2".equals(timeType)) {
			hql += " and billboardTimeQuarter=:billboardTimeQuarter";
			param.put("billboardTimeQuarter", quarter);
		}
		param.put("reportTypeCode", reportTypeId);
		param.put("reportTypeTime", timeType);
		param.put("billboardTime", timeDate);
		param.put("unitId", "%" + unitId + "%");
		Result list = billboardIndustryReportsDAO.hqlParam(hql, param, null);
		if (list != null && list.getOperationResult().size() > 0) {
			List<BillboardIndustryReports> operationResult = (List<BillboardIndustryReports>) list.getOperationResult();
			return operationResult.get(0).getTimeLimit();
		}

		return null;
	}

	public String createBillboardIndustry(BillboardIndustry bIndustry, List<ReportType> cbReportTypes, String users,
			int reportEnd) {
		int reportSum = 0;
		String userIdString = "";
		if (bIndustry == null) {
			// throw new
			// CommonException(ExceptionConstant.MSG_ILLEGAL_PARAMETER);
			log.error("催报信息为空");
			return null;
		}
		String[] split = users.split(",");
		List<String> userIds = new ArrayList<String>();
		for (String userId : split) {
			userIds.add(userId);
		}

		// 获得各催报报表对应的企业数量
		reportSum = cbReportTypes.size() * userIds.size();
		for (int i = 0; i < userIds.size(); i++) {
			if (i == userIds.size() - 1) {
				userIdString += userIds.get(i);
			} else {
				userIdString += userIds.get(i) + ",";
			}
		}
		bIndustry.setOffset(reportEnd);
		bIndustry.setReportSum(reportSum);
		bIndustry.setUsers(userIdString);
		bIndustry.setUserSum(userIds.size());
		if (bIndustry.getId() == null || "".equals(bIndustry.getId()))
			bIndustry.setId(UUID.randomUUID().toString().replaceAll("-", ""));
		billboardIndustryDAO.save(bIndustry);
		List<Unit> units = new ArrayList<Unit>();
		for (String userId : userIdString.split(",")) {
			Unit unit = new Unit();
			unit.setId(userId.trim());
			units.add(unit);
		}
		// 向Scheduler中添加相关Job
		// 向Scheduler中添加相关Job
		// 保存专业与报表类型的关系
		Billboard billboard = new Billboard(UUID.randomUUID().toString().replaceAll("-", ""), bIndustry.getOperator(),
				bIndustry.getBillboardTitle(), bIndustry.getBillboardContent(), new Date(), bIndustry.getId());
		billboardDAO.save(billboard);
		Set<BillboardUser> billboardUsers = new HashSet<BillboardUser>();
		for (Unit user : units) {
			// 默认设置状态为未读，以后有需要判断状态时再进行修改
			BillboardUser billboardUser = new BillboardUser(UUID.randomUUID().toString().replaceAll("-", ""), user,
					billboard, BillboardConstant.STATUS_UNREAD, null);
			billboardUserDAO.save(billboardUser);
			billboardUsers.add(billboardUser);
		}
		billboard.setBillboardUsers(billboardUsers);
		billboardDAO.update(billboard);
		// try {
		// autoPushingScheduler.addJob(bIndustry);
		// } catch (Exception e) {
		// // TODO Auto-generated catch block
		// log.error("创建催报规则错误", e);
		// }

		Map<String, String> statSystems = statSystemService.getStatSystemMap();
		// 保存各催报报表的催报时段信息
		for (ReportType reportType : cbReportTypes) {
			BillboardIndustryReports billboardIndustryReports = new BillboardIndustryReports();
			billboardIndustryReports.setBillboardIndustryId(bIndustry.getId());
			billboardIndustryReports.setReportTypeCode(reportType.getId());
			billboardIndustryReports.setReportTypeName(reportType.getTypeName());
			String type = statSystems.get(reportType.getStatSystem().toString());

			billboardIndustryReports.setReportTypeSystem(type);
			billboardIndustryReports.setReportTypeTime(reportType.getTypeTime());
			billboardIndustryReports.setReportYearTime(reportType.getTypeYearTime());
			billboardIndustryReports.setTimeLimit(reportEnd);
			String typeMeasureUnit = reportType.getTypeMeasureUnit();
			// 修改催报时段
			if (typeMeasureUnit != null) {
				String[] billboardTime = typeMeasureUnit.split("-");
				// 不是季报
				if (billboardTime.length == 1) {
					billboardIndustryReports.setBillboardTime(typeMeasureUnit);
					billboardIndustryReports.setBillboardTimeQuarter("");
				}
				// 季报
				if (billboardTime.length == 2) {
					billboardIndustryReports.setBillboardTime(billboardTime[0]);
					billboardIndustryReports.setBillboardTimeQuarter(billboardTime[1]);
				}
			} else {
				billboardIndustryReports.setBillboardTime(sfd.format(new Date()));
				billboardIndustryReports.setBillboardTimeQuarter("");
			}
			billboardIndustryReports.setId(UUID.randomUUID().toString().replaceAll("-", ""));
			billboardIndustryReportsDAO.save(billboardIndustryReports);
		}

		return bIndustry.getId();
	}

	public String createBillboardRule(BillboardRule rule) {
		if (rule == null || StringUtils.isBlank(rule.getUserIds())) {
			// throw new
			// CommonException(ExceptionConstant.MSG_ILLEGAL_PARAMETER);
			log.error("催报规则为空");
			return null;
		}

		// billboardIndustryDAO.save(rule);
		//
		// // 向Scheduler中添加相关Job
		// try {
		// autoPushingScheduler.addJob(rule);
		// } catch (Exception e) {
		// // TODO Auto-generated catch block
		// log.error("创建催报规则错误", e);
		// }
		return rule.getId();
	}

	public void removeBillboardRule(String id) {
		if (StringUtils.isBlank(id)) {
			// throw new
			// CommonException(ExceptionConstant.MSG_ILLEGAL_PARAMETER);
			return;
		}
		BillboardIndustry bIndustry = billboardIndustryDAO.get(BillboardIndustry.class, id);
		if (bIndustry != null) {
			Filter billFilter = new Filter();
			billFilter.addRule(new FilterRule(FilterConstant.EQUAL, "billboardIndustryId", bIndustry.getId()));
			List<Billboard> list = billboardDAO.find(Billboard.class, billFilter, null);
			for (Billboard bb : list) {
				Filter billUserFilter = new Filter();
				billUserFilter.addRule(new FilterRule(FilterConstant.EQUAL, "billboard.id", bb.getId()));
				List<BillboardUser> userList = billboardUserDAO.find(BillboardUser.class, billUserFilter, null);
				for (BillboardUser bu : userList) {
					billboardUserDAO.delete(bu);
				}
				billboardDAO.delete(bb);
			}

			List<BillboardIndustryReports> brList = billboardIndustryReportsDAO.find(BillboardIndustryReports.class,
					billFilter, null);
			for (BillboardIndustryReports br : brList) {
				billboardIndustryReportsDAO.delete(br);
			}

			billboardIndustryDAO.delete(bIndustry);
		}
	}

}
